import { Entity, ObjectId, ObjectIdColumn, Column, Index, BaseEntity, BeforeInsert, AfterLoad } from 'typeorm'
import dayjs from 'dayjs'

@Entity('user_token')
export default class UserToken extends BaseEntity {
  is_expired: boolean // 是否过期 true: 过期 false: 未过期 根据token_expired_at字段判断

  is_refresh_token_expired: boolean // 是否过期 true: 过期 false: 未过期 根据refresh_token_expired_at字段判断

  @ObjectIdColumn({ comment: 'ID' })
  _id: ObjectId

  @Column('number', { nullable: true, default: null, comment: '用户ID' })
  @Index('user_id_index')
  user_id: number

  @Column('string', { comment: '校验Token' })
  @Index('token_index', { unique: true })
  token: string

  @Column('string', { comment: '刷新Token' })
  refresh_token: string

  @Column('string', { comment: '如果是刷新的则记录被哪个Token刷新的' })
  refreshed_by: string

  @Column('string', { comment: 'Token过期时间，最大2199-12-31 23:59:59' })
  token_expired_at: string

  @Column('string', { comment: 'RefreshToken过期时间，最大2199-12-31 23:59:59' })
  @Index('refresh_token_expired_at_index')
  refresh_token_expired_at: string // refresh_token到期后会自动删除数据

  @Column('boolean', { comment: '是否加黑，一般刷新令牌之后会加黑，加黑则表示不能再使用', default: false })
  is_blacked: boolean

  @BeforeInsert()
  beforeInsert() {
    // 默认未加黑
    this.is_blacked = false
  }

  @AfterLoad()
  afterLoad() {
    this.is_expired = dayjs().isAfter(this.token_expired_at, 's')
    this.is_refresh_token_expired = dayjs().isAfter(this.refresh_token_expired_at, 's')
  }
}
